import { ComponentPublicInstance, createApp, nextTick } from 'vue'
import AppPrompt from './index.vue'

interface AppPromptInstance extends ComponentPublicInstance {
  open: boolean,
  textArea: string,
  show: () => Promise<any>,

  [prop: string]: any
}

let newInstance: AppPromptInstance
let app = null
// 将vue组件进行构造函数转换
const init = (options: any) => {
// 将组件实例化
  const container: any = document.createElement('div')
  app = createApp(AppPrompt)
  newInstance = app.mount(container) as AppPromptInstance
  // 加载dom
  document.body.appendChild(newInstance.$el)
}
const caller = (options: any) => {
  options = {
    ...options
  }
  if (!newInstance) {
    init(options)
  }

  const vm = newInstance
  for (const prop in options) {
    if (options.hasOwnProperty(prop)) {
      vm[prop] = options[prop]
    }
  }
  nextTick().then(() => {
    vm.open = true
    vm.textArea = ''
  })
  return vm.show()
}
export const useAppPrompt = caller
export default {
  install(app: any) {
    app.config.globalProperties.$AppPrompt = caller
  }
}
